"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 二级分区
Case Name   : range_list二级分区表:gs_dump/gs_dumpall
Create At   : 2022/2/18
Owner       : @daiguatutu
Description :
    1.连接数据库并创建新数据库和表空间
    2.在创建好的数据库中创建表并插入查询数据
    3.gs_dump导出数据,指定不同-F参数,gsql/gs_restore方式导入
    4.gs_dumpall导出所有数据,gsql方式导入
    5.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.清理成功
History     :
"""
import os
import unittest
from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Subpartition(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.primaryNode = Node('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.t_name = 't_subpartition_0250'
        self.ts_name = 'ts_subpartition_0250'
        self.db_name_01 = 'db_subpartition_0250_01'
        self.db_name_02 = 'db_subpartition_0250_02'
        self.dump_file = os.path.join(macro.DB_INSTANCE_PATH,
                                      'f_subpartition_0250.sql')

    def test_subpartition(self):
        text = '-----step1:连接数据库并创建新数据库和表空间 expect:成功-----'
        self.log.info(text)
        create_sql = f"drop database if exists {self.db_name_01};" \
            f"drop database if exists {self.db_name_02};" \
            f"create database {self.db_name_01};" \
            f"create database {self.db_name_02};" \
            f"drop table if exists {self.t_name};" \
            f"drop tablespace if exists {self.ts_name};" \
            f"create tablespace {self.ts_name} relative location " \
            f"'{self.ts_name}';"
        msg = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(msg)
        self.assertEqual(2, msg.count(self.constant.CREATE_DATABASE_SUCCESS),
                         '执行失败:' + text)
        self.assertIn(self.constant.TABLESPCE_CREATE_SUCCESS, msg,
                      '执行失败:' + text)

        text = '-----step2:在创建好的数据库中创建表并插入查询数据 expect:成功-----'
        self.log.info(text)
        create_sql = f"create table if not exists {self.t_name}(" \
            f"col_1 int ,col_2 int ,col_3 varchar2 (30) ," \
            f"col_4 int)tablespace {self.ts_name} " \
            f"partition by range (col_1) subpartition by list (col_2) " \
            f"( partition p_range_1 values less than(-10) " \
            f"  ( subpartition p_list_1_1 values('-1','-2','-3','-4','-5')," \
            f"    subpartition p_list_1_2 values(default)), " \
            f"  partition p_range_2 values less than(20) " \
            f"  ( subpartition p_list_2_1 values('6','7','8','9','10'), " \
            f"    subpartition p_list_2_2 values(default)), " \
            f"  partition p_range_3 values less than(30) " \
            f"  ( subpartition p_list_3_1 values(default)), " \
            f"  partition p_range_4 values less than(40) " \
            f"  ( subpartition p_list_4_1 values(default)), " \
            f"  partition p_range_5 values less than(maxvalue) " \
            f") enable row movement; " \
            f"insert into {self.t_name} values(-90,-10,3,8),(-90,10,3,8);" \
            f"insert into {self.t_name} values(90,-10,3,8),(90,10,3,8);" \
            f"insert into {self.t_name} values(-90,-10,3,8),(-100,80,3,8);" \
            f"insert into {self.t_name} values(-90,10,3,8),(100,80,3,8);" \
            f"insert into {self.t_name} values(90,10,3,8);" \
            f"select * from {self.t_name} subpartition (p_list_1_1);" \
            f"select * from {self.t_name} subpartition (p_list_1_1);" \
            f"select * from {self.t_name} subpartition (p_list_2_1);"
        execute_cmd = f'source {macro.DB_ENV_PATH} ;' \
            f'gsql -d {self.db_name_01} -p {self.primaryNode.db_port} ' \
            f'-c "{create_sql}"'
        self.log.info(execute_cmd)
        msg = self.primaryNode.sh(execute_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, msg, '执行失败:' + text)
        self.assertEqual(5, msg.count(self.constant.INSERT_SUCCESS_MSG),
                         '执行失败:' + text)

        text = '-----step3:gs_dump导出数据,指定不同-F参数,gsql/gs_restore方式导入;' \
               ' expect: 成功-----'
        self.log.info(text)
        param_value = ['p', 'c', 'd', 't']
        for value in param_value:
            gs_dump_cmd = f"source {macro.DB_ENV_PATH};" \
                f"rm -rf {self.dump_file};" \
                f"gs_dump {self.db_name_01} -p {self.primaryNode.db_port} " \
                f"-f {self.dump_file} -F {value}"
            self.log.info(gs_dump_cmd)
            msg = self.primaryNode.sh(gs_dump_cmd).result()
            self.log.info(msg)
            self.assertIn(f'dump database {self.db_name_01} successfully',
                          msg, '执行失败:' + text)
            if value == 'p':
                gsql_cmd = f"source {macro.DB_ENV_PATH};" \
                    f"gsql -d {self.db_name_02} " \
                    f"-p {self.primaryNode.db_port} " \
                    f"-f {self.dump_file}"
                self.log.info(gsql_cmd)
                msg = self.primaryNode.sh(gsql_cmd).result()
                self.log.info(msg)
                self.assertIn(self.constant.CREATE_TABLE_SUCCESS, msg,
                              '执行失败:' + text)
                self.assertIn("total time", msg, '执行失败:' + text)
            else:
                gs_restore_cmd = f"source {macro.DB_ENV_PATH};" \
                    f"gs_restore -d {self.db_name_02} " \
                    f"-p {self.primaryNode.db_port} " \
                    f"-F {value} {self.dump_file}"
                self.log.info(gs_restore_cmd)
                msg = self.primaryNode.sh(gs_restore_cmd).result()
                self.log.info(msg)
                self.assertIn('restore operation successful', msg,
                              '执行失败:' + text)

        text = '-----step4:gs_dumpall导出所有数据,gsql方式导入; expect:成功-----'
        self.log.info(text)
        gs_dump_cmd = f"source {macro.DB_ENV_PATH};" \
            f"rm -rf {self.dump_file};" \
            f"gs_dumpall -l {self.db_name_01} " \
            f"-p {self.primaryNode.db_port} " \
            f"-f {self.dump_file} "
        self.log.info(gs_dump_cmd)
        msg = self.primaryNode.sh(gs_dump_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.GS_DUMP_SUCCESS_MSG, msg, '执行失败:' + text)
        gsql_cmd = f"source {macro.DB_ENV_PATH};" \
            f"gsql -d {self.db_name_02} " \
            f"-p {self.primaryNode.db_port} " \
            f"-f {self.dump_file}"
        self.log.info(gsql_cmd)
        msg = self.primaryNode.sh(gsql_cmd).result()
        self.log.info(msg)
        self.assertIn(f'connected to database "{self.db_name_02}"', msg,
                      '执行失败:' + text)
        self.assertIn("total time", msg, '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step5:清理环境-----')
        text_1 = '-----删除数据库,表,表空间 expect:成功-----'
        self.log.info(text_1)
        del_cmd = f'drop database if exists {self.db_name_01};' \
            f'drop database if exists {self.db_name_02};' \
            f'drop table if exists {self.t_name};' \
            f'drop tablespace if exists {self.ts_name};'
        msg = self.pri_sh.execut_db_sql(del_cmd)
        self.log.info(msg)

        text_2 = '-----删除导出的dump文件;expect: 成功-----'
        self.log.info(text_2)
        del_cmd = f"rm -rf {self.dump_file};"
        self.common.get_sh_result(self.primaryNode, del_cmd)
        check_cmd = f'if [ -e {self.dump_file} ]; ' \
            f'then echo "exists"; else echo "not exists"; fi'
        del_msg = self.common.get_sh_result(self.primaryNode, check_cmd)

        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, msg,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, msg,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, msg, '执行失败:' + text_1)
        self.assertEqual('not exists', del_msg, '执行失败:' + text_2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
